import { uploadFileWithUrl } from '/api/file'
import { mallApi } from '/api/mall'
//@ts-ignore
import getMessage from 'ts-msg-handler'
import { GlobalData } from '/store/state'
import { $event } from '/utils'

enum TypeEnum {
  appeal = 'appeal', // 申请投诉
  feedback = 'feedback', // 咨询反馈
  refund = 'refund', // 退款
  refuse_refund = 'refuse_refund', // 驳回退款
  refuse_return = 'refuse_return', // 驳回退货
  return = 'return', // 退货
  negotiate = 'negotiate', // 协商内容填写
  refuse_negotiate = 'refuse_negotiate', // 协商-驳回退款
}
enum DisableEnum {
  appeal = 'appeal', // 禁用申请投诉
  feedback = 'feedback', // 禁用咨询反馈
}

interface QueryOptions {
  orderId?: number // 订单id
  retId?: number // 退款/退货id
  neoId?: number // 协商id
  type?: TypeEnum
  shopkeeper?: boolean
  disable?: DisableEnum
}

Page({
  data: {
    orderId: 0 as number,
    retId: 0 as number,
    neoId: 0 as number,
    type: '' as string,
    shopkeeper: false,
    canAppeal: false,
    orderInfo: {} as any,
    content: '',
    localImages: [] as Array<{ url: string; node?: string }>,
    price: 0,
    score: 0,
    canPublish: false,
    publishing: false,
    currencyName: GlobalData.currencyName,
    navigationHeight: GlobalData.navigationHeight,
    refund_explain: GlobalData.mall.refund_explain || '',

    // 控制页面元素显示
    pageControl: {
      showRadio: false, // 单选按钮
      navigateTitle: '', // 导航栏标题
      inputTitle: '', // 输入框上方标题
      placeholder: '', // 输入框提示信息
    },
    show: false,
  },
  async onLoad(query: QueryOptions) {
    this.setData(
      {
        orderId: query.orderId,
        retId: query.retId,
        neoId: query.neoId,
        type: query.type == TypeEnum.appeal ? TypeEnum.feedback : query.type,
        shopkeeper: !!query.shopkeeper,
        canAppeal: DisableEnum.appeal == query.disable,
      },
      this.computedPage,
    )
  },
  async onShow() {
    if (this.data.orderId) {
      const pages = getCurrentPages()
      const orderInfo =
        pages[pages.length - 2].data.orderInfoTemp || pages[pages.length - 2].data.orderInfo
      this.setData({
        orderInfo,
        price: orderInfo.pay_amount / 100 || 0,
        score: orderInfo.pay_score || 0,
      })
    }
    this.setData({
      currencyName: GlobalData.currencyName,
      navigationHeight: GlobalData.navigationHeight,
      refund_explain: GlobalData.mall.refund_explain || '',
    })
  },
  computedPage() {
    const { type, pageControl } = this.data

    switch (type) {
      case 'appeal':
      case 'feedback':
        pageControl.showRadio = true
        pageControl.navigateTitle = '联系平台'
        pageControl.placeholder = '输入内容'
        break
      case 'refund':
        pageControl.navigateTitle = '填写退款信息'
        pageControl.inputTitle = '退款原因'
        pageControl.placeholder = '输入退款原因，有助于商家更好的处理售后'
        break
      case 'refuse_refund':
        pageControl.navigateTitle = '驳回退款'
        pageControl.inputTitle = '驳回原因'
        pageControl.placeholder = '输入驳回退款申请的原因'
        break
      case 'refuse_return':
        pageControl.navigateTitle = '驳回退货'
        pageControl.inputTitle = '驳回原因'
        pageControl.placeholder = '输入驳回退货申请的原因'
        break
      case 'return':
        pageControl.navigateTitle = '填写退货信息'
        pageControl.inputTitle = '退货原因'
        pageControl.placeholder = '输入退货原因，有助于商家更好的处理售后'
        break
      case 'negotiate':
        pageControl.navigateTitle = '填写协商退款信息'
        pageControl.inputTitle = '协商退款原因'
        pageControl.placeholder = '输入退款原因，有助于商家更好的处理售后'
        break
      case 'refuse_negotiate':
        pageControl.navigateTitle = '驳回退款'
        pageControl.inputTitle = '驳回原因'
        pageControl.placeholder = '输入驳回协商退款申请的原因'
        break
    }
    this.setData({ pageControl })
  },
  showHelp() {
    this.setData({ show: true })
  },
  close() {
    this.setData({ show: false })
  },
  radioChange(e: any) {
    this.setData({ type: e.detail.value })
  },
  inputHandle(e: any) {
    let val = e.detail.value
    const type = e.currentTarget.dataset.type
    if (type === 'price' || type === 'score') {
      val = +val
    }
    this.setData({ [type]: val }, this.canSubmit)
  },
  /** 选中图片 */
  handleImage() {
    if (this.data.localImages.length === 9) {
      wx.showToast({
        title: '你只能最多选择9张照片',
        icon: 'none',
      })
      return
    }

    wx.chooseImage({
      count: 9 - this.data.localImages.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: ({ tempFilePaths }) => {
        const { localImages: images } = this.data
        tempFilePaths.forEach((url) => images.push({ url }))
        if (images.length > 9) {
          wx.showToast({
            title: '你只能最多选择9张照片',
            icon: 'none',
          })
        }
        const localImages = images.length > 9 ? images.splice(0, 9) : images
        this.setData({ localImages }, this.canSubmit)
      },
    })
  },
  /** 取消选择图片 */
  deletImg(e: any) {
    const index = e.currentTarget.dataset.index
    const img = this.data.localImages
    img.splice(index, 1)
    this.setData(
      {
        localImages: img,
      },
      this.canSubmit,
    )
  },
  /** 预览图片 */
  showImages(e: any) {
    const {
      target: {
        dataset: { index },
      },
    } = e
    wx.previewImage({
      urls: this.data.localImages.map((item) => item.url),
      current: this.data.localImages[index].url,
    })
  },
  toDetail(event: WechatMiniprogram.BaseEvent) {
    const data = event.currentTarget.dataset as { id: number; orderId: number }
    wx.navigateTo({ url: `/mall/detail/detail?commodityId=${data.id}&orderId=${data.orderId}` })
  },
  canSubmit() {
    const { content } = this.data
    this.setData({
      canPublish: content !== '',
    })
  },
  async doSubmit() {
    const { publishing, content, price, score, localImages, type, orderId, retId, neoId } =
      this.data
    if (publishing) return
    try {
      wx.showLoading({ title: '处理中' })
      const imgDatas = await Promise.all(
        localImages.map(async (item: any) => {
          return item.node ? item.node : await uploadFileWithUrl(item.url)
        }),
      )
      const images = imgDatas.map((i: any) => {
        return i.node
      })
      let delta = 1
      const priceFen = price * 100
      switch (type) {
        case 'appeal':
          await mallApi.orderAppeal(orderId, { content, images })
          break
        case 'feedback':
          await mallApi.orderFeedback(orderId, { content, images })
          break
        case 'refund': // 退款申请
          await mallApi.postRefund(orderId, {
            type: 'RF_APPLY',
            pay_amount: priceFen,
            pay_score: score,
            reason: content,
            images,
          })
          break
        case 'refuse_refund': // 驳回退款
          await mallApi.rejectRefund(retId, { content, images })
          delta = 2
          break
        case 'return': // 退货申请
          await mallApi.postRefund(orderId, {
            type: 'RT_APPLY',
            pay_amount: priceFen,
            pay_score: score,
            reason: content,
            images,
          })
          break
        case 'refuse_return': // 驳回退货
          await mallApi.rejectReturn(retId, { content, images })
          delta = 2
          break
        case 'negotiate': // 协商退款
          await mallApi.postRefundNegotiate(retId, {
            pay_amount: priceFen,
            pay_score: score,
            reason: content,
            images,
          })
          break
        case 'refuse_negotiate': // 协商-驳回退款
          await mallApi.refuseRefundNegotiate(neoId, { content, images })
          delta = 2
          break
      }

      $event.emit('mallOrderChange')
      wx.showToast({ title: '提交成功' })
      setTimeout(() => {
        wx.navigateBack({ delta })
      }, 1000)
    } catch (error) {
      console.log(error)
      wx.showToast({
        title: `${getMessage(error.data).getMessage() || '提交失败'}`,
        icon: 'none',
      })
      wx.hideLoading()
      this.setData({ publishing: false })
    }
  },
})
